package top.mineidea.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import top.mineidea.pojo.Content;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public  class HtmlParseUtil {
    //    public static void main(String[] args) throws Exception {
//        new HtmlParseUtil().parseJD("vue").forEach(System.out::println);
//    }
    public static List<Content> parseJD(String keyword) throws Exception {
        String url = "https://search.jd.com/Search?keyword=" + keyword;
        Document document = Jsoup.parse(new URL(url), 30000);
        Element list = document.getElementById("J_goodsList");
        Elements elements = list.getElementsByTag("li");
        List<Content> resultList = new ArrayList<>();
        for (Element element : elements) {
            String price = element.getElementsByClass("p-price").eq(0).text();
            String title = element.getElementsByClass("p-name").eq(0).text();
            String img = element.getElementsByTag("img").eq(0).attr("src");
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            resultList.add(content);
        }
        return resultList;
    }

}
